package com.atguigu.tingshu.mq;
import java.math.BigDecimal;
import java.util.Date;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.google.common.collect.Maps;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.model.account.UserAccount;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * Author  王东剑
 * Created on 6/6/2024 PM5:19
 * Package_name com.atguigu.tingshu.mq
 * Description
 */
@Component
@Slf4j
public class AccountReceiver {
	@Autowired
	private UserAccountService userAccountService;
	@KafkaListener(topics = KafkaConstant.QUEUE_USER_REGISTER)
	public void initAccount(ConsumerRecord<String,String> consumerRecord){
		UserAccount userAccount = new UserAccount();
		userAccount.setUserId(Long.parseLong(consumerRecord.value()));
		userAccount.setTotalAmount(new BigDecimal("0"));
		userAccount.setLockAmount(new BigDecimal("0"));
		userAccount.setAvailableAmount(new BigDecimal("0"));
		userAccount.setTotalIncomeAmount(new BigDecimal("0"));
		userAccount.setTotalPayAmount(new BigDecimal("0"));
		userAccountService.save(userAccount);
	}
	@KafkaListener(topics = KafkaConstant.QUEUE_ACCOUNT_MINUS)
	public void minus(ConsumerRecord<String,String> record){
		String orderNo = record.value();
		if(StringUtils.isEmpty(orderNo)) return;
		// 扣减锁定金额
		userAccountService.minus(orderNo);
	}

	@KafkaListener(topics = KafkaConstant.QUEUE_ACCOUNT_UNLOCK)
	public void unlock(ConsumerRecord<String, String> record) {
		String orderNo = record.value();
		if (StringUtils.isEmpty(orderNo)) {
			return;
		}
		userAccountService.unlock(orderNo);
	}

	@KafkaListener(topics = KafkaConstant.QUEUE_RECHARGE_PAY_SUCCESS)
	public void processPaidRecharge(ConsumerRecord<String, String> record) {
		String orderNo = record.value();
		if (StringUtils.isEmpty(orderNo)) {
			return;
		}
		userAccountService.updateRechargeStatus(orderNo);
		log.info("充值记录的订单编号更新成功了.........orderNo: {}",orderNo);
	}
}
